Passed
Push — feature/experience-form-modals ( 37703b...ac040e )
by Tristan
03:52
created

localize.ts ➔ matchValueToModel   A

Complexity

Conditions 2

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
1
import { localizedField, localizedFieldNonNull } from "../models/app";
2
3
export type Locales = "en" | "fr";
4
type TranslatableKeysNonNull<T> = {
5
  [K in keyof T]: T[K] extends localizedFieldNonNull ? K : never;
6
}[keyof T];
7
type TranslatableKeys<T> = {
8
  [K in keyof T]: T[K] extends localizedField ? K : never;
9
}[keyof T];
10
11
export function localizeField<T>(
12
  locale: Locales,
13
  model: T,
14
  field: TranslatableKeys<T>,
15
): string | null {
16
  if (model[field] !== null) {
17
    return model[field][locale];
18
  }
19
  return null;
20
}
21
export function localizeFieldNonNull<T>(
22
  locale: Locales,
23
  model: T,
24
  field: TranslatableKeysNonNull<T>,
25
): string {
26
  return model[field][locale];
27
}
28
29
export function getLocale(locale: string): Locales {
30
  if (locale === "en" || locale === "fr") {
31
    return locale;
32
  }
33
  console.log("Warning: unknown locale. Defaulting to en.");
34
  return "en";
35
}
36
37
export function matchValueToModel<T>(
38
  locale: Locales,
39
  field: TranslatableKeys<T>,
40
  value: string,
41
  possibilities: T[],
42
): T | null {
43
  const matching = possibilities.filter(
44
    (model) => localizeField(locale, model, field) === value,
45
  );
46
  return matching.length > 0 ? matching[0] : null;
47
}
48